<template>
  <div>
    <transition-group
    name="list"
    >
        <div v-for="item in oriDataSource" :key="item[idAttr]" class="tree-item">
            <tree-view-item :item="item" :idAttr="idAttr" :parentAttr="parentAttr" :parentTarget="parentTarget" @expand="expand" @checkedChild="selectChange" :showCheckBox="showCheckBox" :onlyCheckLeaf="onlyCheckLeaf" :disable="disable"></tree-view-item>
        </div>
    </transition-group>

  </div>
</template>

<script>
import Vue from 'vue';
import TreeViewItem from './TreeViewItem.vue';
export default {
  components: { TreeViewItem },
    data(){
        return {
            oriDataSource:[],
            selectItems:[],
        }
    },
    props: {
        dataSource:{
            type: Array,
            required: true
        },
        idAttr:{
            type: String,
            default: 'id'
        },
        parentAttr:{
            type: String,
            default: 'parent'
        },
        parentTarget:{
            type: String,
            default: 'id'
        },
        showCheckBox:{
            type: Boolean,
            default: true
        },
        onlyCheckLeaf:{
            type: Boolean,
            default: false
        },
        disable:{
            type: Function,
            default: ()=>{return true}
        }
    },
    methods:{
        expand(item){            
            Vue.set(item,'__expand',!item.__expand);            
            this.$emit('expand', item)
        },
        getChildren(item,items){
            item.children = this.dataSource.filter(child => child[this.parentAttr] == item[this.parentTarget]);
            if(item.children.length > 0){
                item.children.forEach(child => {
                    this.getChildren(child,items)
                })
            }
        },
        selectChange(item){
            if(item.__checked && this.selectItems.indexOf(item) < 0){
                this.selectItems.push(item)
            }else if(!item.__checked && this.selectItems.indexOf(item) >= 0){
                this.selectItems.splice(this.selectItems.indexOf(item),1)
            }
            this.$emit('selectChange', item,item.__checked)
        }
    },
    mounted(){
        this.oriDataSource = this.dataSource.filter(item => !item[this.parentAttr]);
        this.oriDataSource.forEach(item => {
            this.getChildren(item,this.dataSource)
        });
    },
    
}
</script>

<style scoped>
.list-item {
  display: inline-block;
  margin-right: 10px;
}
.list-enter-active, .list-leave-active {
  transition: all 0.3s;
}
.list-enter, .list-leave-to
/* .list-leave-active for below version 2.1.8 */ {
  opacity: 0;
  transform: translateX(10px);
}
</style>